package com.dapeis.web.wx.spring.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ag.core.exception.NoLoginException;
import com.dapeis.domain.User;
import com.dapeis.exception.user.WechatNotOpenIdUserException;
import com.dapeis.service.UserService;
import com.dapeis.web.wx.controller.RestController;
import com.dapeis.web.wx.utils.threadloca.WxUserThreadLocal;

/**
 * 微信openId拦截入口 Title:StylistUserAuthApiInterceptor.java
 * StylistUserAuthApiInterceptor Description:
 * 
 * @author yuanyong
 * @date 2017年4月20日 下午4:30:09 Email: hzyuanyong@126.com
 *
 */
public class WxOpenIdAuthApiInterceptor implements HandlerInterceptor {
    final Logger logger = LoggerFactory.getLogger(getClass());
    public static WxUserThreadLocal userThreadLocal = new WxUserThreadLocal();
    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request,
	    HttpServletResponse response, Object handler) throws Exception {
	// Integer userId = ApiTokenUtils.tokenCheckAndGet(request,
	// ApiTokenUtils.USER_REDIS_PRE_KEY);
	String openId = request.getHeader("openId");
	userThreadLocal.resetUserId(openId);
	User user = RestController.getThreadLocalUser();
	if (user == null) {
	    String msg = "该openId未注册用户!";
	    if (StringUtils.isBlank(openId)) {
		msg = "openId 为空!";
	    }
	    throw new WechatNotOpenIdUserException(msg);
	}
	userService.checkUserVaild(user);
	return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
	    HttpServletResponse response, Object handler,
	    ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
	    HttpServletResponse response, Object handler, Exception ex)
	    throws Exception {
	userThreadLocal.remove();
    }

}
